package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVO;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockLockedDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public void unLockStock(StockLockedTo stockLockedTo) {
        StockLockedDetailTo detail = stockLockedTo.getDetail();
        // 库存工作单ID
        Long taskId = stockLockedTo.getTaskId();
        // 库存工作单详情ID
        Long taskDetailId = detail.getId();
        // 第一步 查询数据库，关于这个订单的锁定库存信息

        WareOrderTaskDetailEntity detailEntity = orderTaskDetailService.getById(taskDetailId);
        if (detailEntity != null) {
            // 有记录：库存服务没问题，以及锁定成功了，到底要不要解锁，还要检查订单
            // 1.没有订单，必须解锁
            // 2.有订单，不是解锁库存,要看订单状态，只要没取消，不能解锁
            WareOrderTaskEntity taskEntity = orderTaskService.getById(taskId);
            // 根据订单号，查询订单状态，只有订单以取消，才能解锁库存
            R r = orderFeignService.getOrderStatus(taskEntity.getOrderSn());
            if (r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {
                });
                // 订单不存在 或者 订单取消，都要回滚
                //订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭(取消)；5->无效订单】
                if (orderVo == null || orderVo.getStatus() == 4) {
                    // 订单已经被取消了，要解锁库存
                    unLockStock(
                            detail.getSkuId(),
                            detail.getWareId(),
                            detail.getSkuNum(),
                            detail.getId());
                }
            } else {
                throw new RuntimeException("远程服务调用失败");
            }
        } else {
            // 没有记录：库存锁定失败，库存回滚了，无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致状态一直改不了，库存消息优先到期，查询订单还是新建状态，什么都不做
     * 导致库存永远解锁不了
     *
     * @param orderTo
     */
    @Override
    @Transactional
    public void unLockStock(OrderTo orderTo) {
        // 使用库存工作单，来解锁
        // 查询库存工作单主表
        WareOrderTaskEntity orderTask = orderTaskService.getOrderTaskByOrderSn(orderTo.getOrderSn());
        // 查询工作单详情
        List<WareOrderTaskDetailEntity> detailList = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", orderTask.getId())
                        .eq("lock_status", 1)
        );
        for (WareOrderTaskDetailEntity detail : detailList) {
            unLockStock(detail.getSkuId(),
                    detail.getWareId(),
                    detail.getSkuNum(),
                    detail.getId());
        }
    }

    public void unLockStock(Long skuId, Long wareId, Integer num, Long taskdetailId) {
        // 库存锁定状态：1-以锁定。2-解锁。3-扣减
        // 检查库存工作单状态，只有1-以锁定 才能解锁
        WareOrderTaskDetailEntity detailEntity = orderTaskDetailService.getById(taskdetailId);
        if (detailEntity != null && detailEntity.getLockStatus() == 1) {
            // 执行解锁
            wareSkuDao.unLockStock(skuId, wareId, num);
            // 库存解锁成功，更新库存工作单状态为，已解锁
            detailEntity.setLockStatus(2);
            orderTaskDetailService.updateById(detailEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }


            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVO> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVO> skuHasStockVOS = skuIds
                .stream()
                .map(skuId -> {
                    SkuHasStockVO vo = new SkuHasStockVO();
                    // 查询当前sku的总库存量
                    Long count = baseMapper.getSkuStock(skuId);
                    vo.setSkuId(skuId);
                    vo.setHasStock(count == null ? false : count > 0);
                    return vo;
                })
                .collect(Collectors.toList());
        return skuHasStockVOS;
    }

    /**
     * 为某个订单 锁定库存
     * <p>
     * 库存解锁的场景：
     * 1、下单成功，没有支付，自动取消/用户手动取消
     * 2、下订单成功，库存锁定成功，其他业务调用， 导致订单回滚，之前锁定的库存就要解锁
     * 3、
     *
     * @param wareSkuLockVo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        // 保存库存工作单的详情,追溯
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        orderTaskService.save(orderTaskEntity);

        // 找到每个商品，在哪个仓库有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            // 查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        // 锁定库存
        for (SkuWareHasStock skuWareHasStock : collect) {
            boolean skuStock = false;
            Long skuId = skuWareHasStock.getSkuId();
            Integer num = skuWareHasStock.getNum();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (!CollectionUtils.isEmpty(wareIds)) {
                // 遍历 锁定库存
                /**
                 * 1、如果每个商品都锁定成功，将当前商品锁定了几件的工作单记录发给MQ
                 * 2、如果 锁定失败，前面保存的工作单就回滚了，发送出去的消息，即使要解锁，去数据库查不到工作单，所以也不用解锁
                 */
                for (Long wareId : wareIds) {
                    // 返回受影响行数，成功就返回1，否则返回0
                    Integer count = wareSkuDao.lockSkuStock(skuId, wareId, num);
                    if (count == 0) {
                        // 当前仓库锁失败
                    } else {
                        // 锁定成功
                        skuStock = true;
                        // 保存库存工作单详情
                        WareOrderTaskDetailEntity taskDetail = new WareOrderTaskDetailEntity();
                        taskDetail.setTaskId(orderTaskEntity.getId());
                        taskDetail.setSkuId(skuId);
                        taskDetail.setSkuNum(num);
                        taskDetail.setSkuName("");
                        taskDetail.setWareId(wareId);
                        taskDetail.setLockStatus(1);
                        orderTaskDetailService.save(taskDetail);
                        // todo 发送消息，告诉MQ 库存锁定成功
                        StockLockedTo stockLockedTo = new StockLockedTo();
                        stockLockedTo.setTaskId(orderTaskEntity.getId());
                        StockLockedDetailTo detailTo = new StockLockedDetailTo();
                        BeanUtils.copyProperties(taskDetail, detailTo);
                        // 只发ID不行，防止前面几次成功，回滚后找不到数据
                        stockLockedTo.setDetail(detailTo);
                        rabbitTemplate.convertAndSend(
                                "stock-event-exchange",
                                "stock.locked",
                                stockLockedTo);
                        break;
                    }
                }
            } else {
                throw new NoStockException(skuId);
            }
            if (!skuStock) {
                // 当前商品 所有仓库都没锁住，没库存
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}